/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-10
 * Time: 13:30
 */
class MyBlockingQueue{
    public int[] elem;
    public volatile int head;
    public volatile int tail;
    public volatile int size;
    public MyBlockingQueue(int capacity){
        this.elem=new int[capacity];
    }
    public void put(int value) throws InterruptedException {
        synchronized(this) {
            while (size >= elem.length) {
                //队列满了,阻塞等待
              this.wait();
            }
            elem[tail] = value;
            tail++;
            size++;
            if (tail == elem.length) {
                tail = 0;
            }
            this.notify();
        }
    }
    public int take() throws InterruptedException {
        synchronized (this) {


            while (size == 0) {
                //队列为空,阻塞等待
                this.wait();

            }
            int str = elem[head];
            head++;
            if (head >= elem.length) {
                head = 0;
            }
            size--;
            this.notify();
            return str;

        }
    }
}
public class Demo1 {
    public static int count=1;
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue=new MyBlockingQueue(10);
        Thread t1=new Thread(()->{
            while(true){

                try {
                    myBlockingQueue.put(count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t1 生产:"+count);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
            }
        });
        Thread t2=new Thread(()->{
            while(true){
                int tmp= 0;
                try {
                    tmp = myBlockingQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t2 消费:"+tmp);


            }
        });
        t1.start();
        t2.start();

    }
}
